import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  DeviceEventEmitter,
  Platform,
  Image,
  Alert,
  Animated,
  TouchableOpacity,
  Dimensions,
  NativeAppEventEmitter,
  InteractionManager,
  TextInput,
} from 'react-native';

import ScrollableTabView from 'react-native-scrollable-tab-view';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';
import NormalList from './delivery/normalList';
import styles from './ownerInfoStyle';
import api from 'services/api';
import ToastTip from '../global/ToastTip';
import {
  ROOM_INFO,//房屋信息
  BASE,//基础信息
  URGENCY,//紧急联系
  POST_ADDRESS,//邮寄地址
  FAMILY_INFO,//家庭人员
  CAR_NUM,//车辆数量
  CAR_INFO,//车辆信息
  GENDER,//性别
} from './delivery/deliveryConst';

import selfStyles from './delivery/style';

import Touch from '../global/Touch';
import SimpleDialog from '../global/SimpleViewDialog';

class DeliveryDetail extends Component {
  constructor(props) {
		super(props);
    let {id} = props;
		this.state = {
			isLoading: true,
      id,
      data:{
        roomInfo:{},//房屋信息,
        personalInfo:{},//基础信息
        carInfo:{},//车辆信息
        familyInfo:[],//家庭信息
        status:null,
        last_record_id:null,
      },
      passDialog:false,
      rejectDialog:false
		};

	}

  componentWillMount() {
    this.doFetch();
	}

  async doFetch(){
    let {id} = this.state;
    let result = await api.get('/delivery/getDeliveryDetailGJ' ,{ownerId:id});
    if(result.cd != 0){
      return
    }
    this.setState({
      data:result.data||{}
    })
  }

  componentDidMount(){
  }

  //驳回
  reject = () => {
    this.refs.rejectDialog.open()
  }

  //通过
  pass = () => {
    this.refs.passDialog.open()
  }

  //底部按钮
  renderBottomBtn(status){
    if(status == 1){
      return (
        <View style={selfStyles.btnWraper}>
          <Touch 
            style={[selfStyles.btn]}
            onPress={this.reject}
          >
            <Text style={selfStyles.btnText}>驳回</Text>
          </Touch>
          <Touch 
            style={[selfStyles.btn,{backgroundColor:'#EA5404'}]}
            onPress={this.pass}
          >
            <Text style={[selfStyles.btnText,{color:'#fff'}]}>通过</Text>
          </Touch>
        </View>
      )
    }
    if(status == 2){
      return (
        <View style={selfStyles.btnWraper}>
          <Touch 
            style={[selfStyles.btn,{backgroundColor:'#EA5404'}]}
            onPress={() => {
              this.props.navigator.pop()
            }}
          >
            <Text style={[selfStyles.btnText,{color:'#fff'}]}>返回</Text>
          </Touch>
        </View>
      )
    }
    if(status == 3){
      return (
        <View style={selfStyles.btnWraper}>
          <Touch 
            style={[selfStyles.btn,{backgroundColor:'#EA5404'}]}
            onPress={this.pass}
          >
            <Text style={[selfStyles.btnText,{color:'#fff'}]}>通过</Text>
          </Touch>
        </View>
      )
        
    }
  }

  render() {
    let {data,passDialog,rejectDialog} = this.state;
    let {
      roomInfo={},
      personalInfo={},
      carInfo={},
      familyInfo=[],
      status
    } = data;
    if(status === null) {
      return (
        <ListViewActivityIndicator
          ref={ (component) => this._activityIndicator = component }
          color={'#a9a9a9'}
          style={{margin:'auto',marginTop:10}}
        />
      )
    }
    return (
      <View style={styles.container}>
        <ScrollView>
          <View>
            <Text style={selfStyles.typeTitle}>房屋信息</Text>
            <View style={selfStyles.secBody}>
              {Object.keys(ROOM_INFO).map((key,index) => {
                return (
                  <View key={index} style={selfStyles.row}>
                    <Text style={selfStyles.th75}>{ROOM_INFO[key]}</Text>
                    <Text style={selfStyles.td}>{roomInfo[key]||'-'}{key=='area'?'㎡':''}</Text>
                  </View>
                )
              })}
            </View>
          </View>
          <View>
            <Text style={selfStyles.typeTitle}>基础信息</Text>
            <View style={selfStyles.secBody}>
              {Object.keys(BASE).map((key,index) => {
                return (
                  <View key={index} style={selfStyles.row}>
                    <Text style={selfStyles.th75}>{BASE[key]}</Text>
                    {key == 'gender'?
                      <Text style={selfStyles.td}>{GENDER[personalInfo[key]]}</Text>
                      :
                      <Text style={selfStyles.td}>{personalInfo[key]||'-'}</Text>
                    }
                  </View>
                )
              })}
            </View>
          </View>
          <View>
            <Text style={selfStyles.typeTitle}>紧急联系</Text>
            <View style={selfStyles.secBody}>
              {Object.keys(URGENCY).map((key,index) => {
                return (
                  <View key={index} style={selfStyles.row}>
                    <Text style={selfStyles.th75}>{URGENCY[key]}</Text>
                    <Text style={selfStyles.td}>{personalInfo[key]||'-'}</Text>
                  </View>
                )
              })}
            </View>
          </View>
          <View>
            <Text style={selfStyles.typeTitle}>邮寄地址</Text>
            <View style={selfStyles.secBody}>
              {Object.keys(POST_ADDRESS).map((key,index) => {
                return (
                  <View key={index} style={selfStyles.row}>
                    <Text style={selfStyles.th75}>{POST_ADDRESS[key]}</Text>
                    <Text style={selfStyles.td}>{personalInfo[key]||'-'}</Text>
                  </View>
                )
              })}
            </View>
          </View>
          <View>
            <Text style={selfStyles.typeTitle}>家庭人员</Text>
            <View style={selfStyles.secBody}>
              {familyInfo.map((item,index) => {
                return (
                  <View key={index}>
                    <View style={selfStyles.itemTitle}>
                      <Text>家庭成员{index+1}</Text>
                    </View>
                    {Object.keys(FAMILY_INFO).map((key,i) => {
                      return (
                        <View key={i} style={selfStyles.row}>
                          <Text style={selfStyles.th100}>{FAMILY_INFO[key]}</Text>
                          {key == 'gender'?
                            <Text style={selfStyles.td}>{GENDER[item[key]]}</Text>
                            :
                            <Text style={selfStyles.td}>{item[key]||'-'}</Text>
                          }
                        </View>
                      )
                    })}
                  </View>
                )
              })}
            </View>
          </View>
          <View>
            <Text style={selfStyles.typeTitle}>车辆数量</Text>
            <View style={selfStyles.secBody}>
              {Object.keys(CAR_NUM).map((key,index) => {
                return (
                  <View key={index} style={selfStyles.row}>
                    <Text style={selfStyles.th100}>{CAR_NUM[key]}</Text>
                    <Text style={selfStyles.td}>{carInfo[key]||'-'}</Text>
                  </View>
                )
              })}
            </View>
          </View>
          {Array.isArray(carInfo.carInfoList) && carInfo.carInfoList.length > 0?
            <View >
              <Text style={selfStyles.typeTitle}>车辆信息</Text>
              <View style={selfStyles.secBody}>
                {(carInfo.carInfoList||[]).map((item,index) => {
                  return (
                    <View key={index}>
                      <View style={selfStyles.itemTitle}>
                        <Text>车辆{index+1}</Text>
                      </View>
                      {Object.keys(CAR_INFO).map((key,i) => {
                        return (
                          <View key={i} style={selfStyles.row}>
                            <Text style={selfStyles.th100}>{CAR_INFO[key]}</Text>
                            <Text style={selfStyles.td}>{item[key]||'-'}</Text>
                          </View>
                        )
                      })}
                    </View>
                  )
                })}
              </View>
            </View>:null
          }
          <View style={{height:50}}/> 
        </ScrollView>
        {this.renderBottomBtn(status)}

        <ApproveDialog 
          ref='passDialog' callback={this.doFetch.bind(this)}
          approveStatus={1} 
          ownerId={personalInfo.ownerId} 
          record_id={data.last_record_id}
          callback={this.doFetch.bind(this)}
        />
        <ApproveDialog 
          ref='rejectDialog' 
          approveStatus={0} 
          ownerId={personalInfo.ownerId} 
          record_id={data.last_record_id}
          callback={this.doFetch.bind(this)}
        />
        
      </View>
    );
  }
}

class ApproveDialog extends Component {
  constructor(props){
    super(props);
    this.state = {
      open:false,
      text:'',
      isLoading:false
    }
  }

  open(){
    this.setState({open:true})
  }

  hide(){
    this.setState({open:false})
  }

  //审核
  async approve(){
    this.setState({isLoading:true})

    let {text} = this.state;
    let {approveStatus,ownerId,record_id} = this.props;
    let params = {
        ownerId,
        record_id,
        isApprove:approveStatus
    }
    if(approveStatus == 0){
      params.rejectReason = text
    }
    let result = await api.post('/delivery/approveDeliveryInfo',params);
    if(result.cd != 0){
      this.refs.toast.show(result.msg);
      return
    }
    let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
    Emitter.emit('delivery.count.onload');
    Emitter.emit('delivery.onload');
    this.props.callback();
    this.setState({open:false,isLoading:false})
  }

  closeDialog = () => {
    if(this.state.isLoading){
      return
    }
    this.setState({open:false})
  }

  //审核通过
  renderPassDialog(){
    return (
      <View style={{marginVertical:25,alignItems:'center'}}>
        <Text style={{fontSize:15,color:'#7B7B7B'}}>确认通过?</Text>
      </View>
    )
  }

  //驳回
  renderRejectDialog(){
    let {text} = this.state;
    return (
      <View style={{padding:15,}}>
        <View style={{position:'relative'}}>
          <TextInput
            style={{
              height: 110,
              paddingBottom:15,
              paddingVertical:5, 
              color:'#565656',
              borderColor: '#ddd', 
              borderWidth: StyleSheet.hairlineWidth,
              justifyContent:'flex-start'
            }}
            autoFocus={true}
            textAlignVertical='top'
            multiline={true}
            underlineColorAndroid={'transparent'}
            onChangeText={(text) => this.setState({text})}
            value={this.state.text}
            placeholder='输入内容请少于100字'
            maxLength={100}
            placeholderTextColor='#B5B5B5'
          />
          <Text 
            style={{
              position:'absolute',
              bottom:5,
              right:10,
              fontSize:12,
              color:'#B5B5B5'
            }}
          >{text.length}/100</Text>
        </View>
      </View>
    )
  }

  renderOptionBtn(){
    let {open,text,isLoading} = this.state;
    let {approveStatus} = this.props;
    if(isLoading){
      return (
        <View 
          style={[
            selfStyles.dialog_btn,
            {marginLeft:15,backgroundColor:'#EA5404',borderWidth:0,flexDirection:'row'}
          ]}>
          <ListViewActivityIndicator
            visible={'visible'}
            color={'#fff'}
          />
          <Text style={[selfStyles.dialog_btn_text,{color:'#fff'}]}>处理中</Text>
        </View>
      )
    }
    if(approveStatus==0 && text.length == 0){
      return (
        <View style={[selfStyles.dialog_btn,{marginLeft:15,backgroundColor:'#ddd',borderWidth:0}]}>
          <Text style={[selfStyles.dialog_btn_text,{color:'#b5b5b5'}]}>确认</Text>
        </View>
      )
    }
    return (
      <Touch 
        onPress={this.approve.bind(this)}
        style={[selfStyles.dialog_btn,{marginLeft:15,backgroundColor:'#EA5404',borderWidth:0}]}
      >
        <Text style={[selfStyles.dialog_btn_text,{color:'#fff'}]}>
          {approveStatus==1?'通过':'确认'}
        </Text>
      </Touch>
    )
  }


  render(){
    let {open,text,isLoading} = this.state;
    let {approveStatus} = this.props;
    return (
      <SimpleDialog
        open={open}
        closeOnTouchOutside={false}
        modalStyle={{padding:0,overflow:'hidden'}}
        modalDidOpen={() => {}}
        style={{alignItems: 'center'}}
        ref='passDialog'
      >
        <View style={selfStyles.dialogHeader}>
          <Text style={selfStyles.headerText}>
          {approveStatus==1?'温馨提示':'请输入驳回原因'}
          </Text>
          <TouchableOpacity 
            style={selfStyles.dialog_close}
            onPress={this.closeDialog}
            activeOpacity={0.8}
          >
            <Image source={require('img/dialog_close.png')}/>
          </TouchableOpacity>
        </View>
        {approveStatus==1?this.renderPassDialog():this.renderRejectDialog()}
        <View style={selfStyles.dialog_btn_wraper}>
          <Touch 
            style={selfStyles.dialog_btn}
            onPress={this.closeDialog}
          >
            <Text style={selfStyles.dialog_btn_text}>取消</Text>
          </Touch>
          {this.renderOptionBtn()}
        </View>
        <ToastTip ref="toast"   position='top' positionValue={50}/>
      </SimpleDialog>

    )
  }
}

var connectHelper = require('../../services/connectHelper');
DeliveryDetail = connectHelper(state => state)(DeliveryDetail);

module.exports = DeliveryDetail;
